<template>
  <div class="flex w-screen h-screen justify-center">
    <div class="flex flex-col">
      <div class="flex w-[1000px] h-[460px] justify-center">
        <div
          class="flex flex-col px-[20px] py-[30px] rounded-[20px] bg-gradient-to-t from-red-100 to-blue-100 mt-[20px]"
        >
          <div class="w-[1000px] h-[52px] flex justify-center">
            <p class="text-[15px]">
              未来30天将有13天下雨，有1天温度超过35°，最高温36°（09月05日），最低温17°（09月27日）。
            </p>
          </div>
          <!-- 天气卡片和天气日历 -->
          <div class="flex justify-between">
            <!-- 周和日历 -->
            <div class="flex flex-col">
              <div
                class="w-[709px] h-[16px] flex text-[12px] text-center pb-[10px] text-gray-800"
              >
                <p class="flex-1">日</p>
                <p class="flex-1">一</p>
                <p class="flex-1">二</p>
                <p class="flex-1">三</p>
                <p class="flex-1">四</p>
                <p class="flex-1">五</p>
                <p class="flex-1">六</p>
              </div>
              <div class="w-[709px] h-[307.76px] flex flex-wrap">
                <div
                  class="m-[2.5px] w-[96.24px] h-[57.33px] rounded-[10px]"
                ></div>
                <div
                  class="m-[2.5px] w-[96.24px] h-[57.33px] rounded-[10px]"
                ></div>
                <div
                  class="m-[2.5px] w-[96.24px] h-[57.33px] rounded-[10px]"
                ></div>
                <div
                  class="m-[2.5px] w-[96.24px] h-[57.33px] rounded-[10px]"
                ></div>
                <div v-for="item in msg" v-bind:item="item">
                  <div
                    v-bind:class="{
                      '!bg-[#427BFF]': item.fxDate === selectDate,
                    }"
                    v-on:click="onSelectDate(item.fxDate)"
                    class="m-[2.5px] w-[96.24px] h-[57.33px] rounded-[10px] bg-white hover:bg-[#427BFF] cursor-pointer flex flex-col"
                  >
                    <div class="text-[12px]">
                      {{ item.fxDate }}
                      <i v-bind:class="`qi-${item.iconDay} text-red-500`"></i>
                      <p class="text-[12px]">
                        {{ item.tempMin }}°~{{ item.tempMax }}°
                      </p>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <!-- 天气卡片 -->
            <div class="flex flex-col h-[323px] w-[222px]">
              <div class="flex w-[220px] h-[25px] justify-center items-center">
                <p class="mx-2">高温</p>
                <p class="mx-2">低温</p>
              </div>
              <div
                class="flex flex-col w-[220px] h-[304px] bg-white rounded-lg"
              >
                <div class="flex items-center w-[220px] h-[46px]">
                  {{ selectDetail.fxDate }}
                </div>
                <div class="w-[220px] h-[1.5px] bg-slate-100"></div>
                <div class="flex flex-col items-center w-[220px] h-[240px]">
                  <div class="flex items-center w-[200px] h-[62px]">
                    <div class="w-[128px] h-[51px]">
                      <p class="text-xl">
                        {{ selectDetail.tempMax }} °~
                        {{ selectDetail.tempMin }}°
                      </p>
                      <p>{{ selectDetail.textDay }}</p>
                    </div>
                    <div class="flex justify-center w-[61px]">
                      <i
                        v-bind:class="`qi-${selectDetail.iconDay} text-[40px]`"
                      ></i>
                    </div>
                  </div>
                  <div class="flex justify-between w-[200px] h-[40px] mt-2">
                    <div class="w-[87px] h-[40px]">
                      <p>{{ selectDetail.windScaleDay }}级</p>
                      <p class="text-[#00000080]">
                        {{ selectDetail.windDirDay }}
                      </p>
                    </div>
                    <div class="w-[87px] h-[40px]">
                      <p>{{ selectDetail.precip }}mm</p>
                      <p class="text-[#00000080]">降水量</p>
                    </div>
                  </div>
                  <div class="flex justify-between w-[200px] h-[40px] mt-4">
                    <div class="w-[87px] h-[40px]">
                      <p>{{ selectDetail.windScaleDay }}</p>
                      <p class="text-[#00000080]">紫外线</p>
                    </div>
                    <div class="w-[87px] h-[40px]">
                      <p>{{ selectDetail.humidity }}%</p>
                      <p class="text-[#00000080]">空气湿度</p>
                    </div>
                  </div>
                  <div class="flex justify-between w-[200px] h-[40px] mt-4">
                    <div class="w-[87px] h-[40px]">
                      <p>{{ selectDetail.sunrise }}</p>
                      <p class="text-[#00000080]">日出</p>
                    </div>
                    <div class="w-[87px] h-[40px]">
                      <p>{{ selectDetail.sunset }}</p>
                      <p class="text-[#00000080]">日落</p>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 图表 -->
      <div class="flex w-[1015px] h-[1200px]">
        <div class="flex justify-center mt-4">
          <div
            class="rounded-lg shadow-md p-4 border mb-8 "
            style="width: 640px; height: 418px"
          >
            <h2 class="text-center text-lg font-semibold mb-4">过往十天气温曲线</h2>
              <div ref="chartRef" class="w-full h-80 bg-gray-50 rounded-lg"></div>
          </div>
          <!-- 表格 -->
          <div
            class="flex flex-col items-center w-[353px] ml-5 bg-[#F7F8F9] rounded-lg"
          >
            <div class="text-[22px] mt-5">附近城市</div>

            <div
              class="flex items-center w-[310px] h-[45px] mt-3 bg-slate-100 rounded-lg"
            >
              <p class="flex text-[20px] p-2.5">武汉市</p>
              <i
                v-bind:class="`qi-${msg[0].iconDay} text-[40px]`"
                class="pl-[85px]"
              ></i>
              <div class="text-[#000000] text-[20px] pl-[20px]">
                {{ msg[0].tempMax }}°~{{ msg[0].tempMin }}°
              </div>
            </div>
            <div v-for="item in storedWeatherData">
              <div
                class="flex items-center w-[310px] h-[45px] mt-3 bg-slate-100 rounded-lg"
              >
                <p class="flex text-[20px] p-2.5">{{ item.name }}</p>
                <i
                  v-bind:class="`qi-${item.iconDay} text-[40px]`"
                  class="pl-[85px]"
                ></i>
                <div class="text-[#000000] text-[20px] pl-[20px]">
                  {{ item.maxTemp }}°~{{ item.minTemp }}°
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import axios from "axios";
import { ref, computed,} from "vue";



const userLatitude = ref(null);
const userLongitude = ref(null);
//数据储存
var msg = ref([]); //天气数据
var selectDate = ref(""); //选中日期数据
const recentDays = ref([]);//进十天数据

//获取用户位置信息
window.navigator.geolocation.getCurrentPosition(
  (position) => {
    userLatitude.value = position.coords.latitude.toFixed(2);
    userLongitude.value = position.coords.longitude.toFixed(2);
    getWeather(userLongitude.value, userLatitude.value)
    fetchRecentTenDaysWeather(userLongitude.value, userLatitude.value);
  },
  (error) => {
    console.log("定位失败:", error);
  },
  { enableHighAccuracy: true }
);


function onSelectDate(date) {
  selectDate.value = date;
}

//卡片信息
var selectDetail = computed(function () {
  return msg.value.find((item) => item.fxDate === selectDate.value);
});
function getWeather(longitude, latitude) {
  var host = "https://p76yvxv44n.re.qweatherapi.com";
  var token =
    "Bearer eyJhbGciOiJFZERTQSIsImtpZCI6Iks0NUY1R0pRTVAifQ.eyJzdWIiOiI0OVRORjZRRUpWIiwiaWF0IjoxNzU3NTcwODgyLCJleHAiOjE3NTc2NTcyODJ9.tgyV0Ric5fuBRXxJjsF-p9k9qafhmprj7L-49FibuLDxj6iWMUh4VAjYrC7UJ-kFpo8kawH-2OLa20SI1h-ICQ";
 
    axios
  .get(`${host}/v7/weather/30d`, {
    params: {
      location: `${longitude},${latitude}`,
    },
    headers: {
      Authorization: token,
    },
  })
  .then(function (response) {
    msg.value = response.data.daily;
    selectDate.value = response.data.daily[0].fxDate;
  });  
  };


// 图表容器
const chartRef = ref(null);


// 获取过往十天天气数据
async function fetchRecentTenDaysWeather(longitude, latitude) {
  const host = "https://p76yvxv44n.re.qweatherapi.com";
  const token =
    "Bearer eyJhbGciOiJFZERTQSIsImtpZCI6Iks0NUY1R0pRTVAifQ.eyJzdWIiOiI0OVRORjZRRUpWIiwiaWF0IjoxNzU3NTcwODgyLCJleHAiOjE3NTc2NTcyODJ9.tgyV0Ric5fuBRXxJjsF-p9k9qafhmprj7L-49FibuLDxj6iWMUh4VAjYrC7UJ-kFpo8kawH-2OLa20SI1h-ICQ";

  try {
    // 获取城市ID
    const geoResponse = await axios.get(`/api/geo/v2/city/lookup`, {
      params: { location: `${longitude},${latitude}` },
      headers: { Authorization: token },
    });

    const locationId = geoResponse.data.location[0].id;

    // 获取最近10天日期
    const today = new Date();
    const dates = [];
    for (let i = 9; i >= 0; i--) {
      const date = new Date(today);
      date.setDate(date.getDate() - i-1);
      const ymd = date.toISOString().split('T')[0];
      dates.push(ymd);
    }

    // 并发请求
    const promises = dates.map(async (date) => {
      const formattedDate = date.replace(/-/g, '');
      try {
        const response = await axios.get(`${host}/v7/historical/weather`, {
          params: {
            location: locationId,
            date: formattedDate,
          },
          headers: { Authorization: token },
        });
        if (response.data.code === "200") {
          return {
            date: date,
            tempMax: response.data.weatherDaily.tempMax,
            tempMin: response.data.weatherDaily.tempMin,
            avgTemp: ((parseInt(response.data.weatherDaily.tempMax) + parseInt(response.data.weatherDaily.tempMin)) / 2).toFixed(1),
            precip: response.data.weatherDaily.precip,
          };
        }
      } catch (error) {
        console.warn(`获取 ${date} 失败:`, error);
        return null;
      }
    });

    const results = await Promise.all(promises);
    recentDays.value = results.filter(item => item !== null);

  // 渲染图表
    renderChart();
  } catch (error) {
    console.error("获取最近十天天气失败:", error);
  }
}

// 渲染 ECharts 图表
function renderChart() {
  if (!window.ECharts) {
    console.warn("ECharts 未加载");
    return;
  }

  const myChart = window.ECharts.init(chartRef.value);
  const data = recentDays.value;

  const dates = data.map(d => d.date);
  const maxTemps = data.map(d => parseFloat(d.tempMax));
  const minTemps = data.map(d => parseFloat(d.tempMin));
  const avgTemps = data.map(d => parseFloat(d.avgTemp));

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['最高温度', '最低温度', '平均温度']
    },
    xAxis: {
      type: 'category',
      data: dates,
      axisLabel: {
        rotate: 45
      }
    },
    yAxis: {
      type: 'value',
      name: '温度 (°C)',
      min: 0,
      max: 40,
      interval: 10
    },
    series: [
      {
        name: '最高温度',
        type: 'line',
        data: maxTemps,
        lineStyle: { color: '#ef4444' },
        areaStyle: { color: '#ef4444', opacity: 0.1 }
      },
      {
        name: '最低温度',
        type: 'line',
        data: minTemps,
        lineStyle: { color: '#3b82f6' },
        areaStyle: { color: '#3b82f6', opacity: 0.1 }
      },
      {
        name: '平均温度',
        type: 'line',
        data: avgTemps,
        lineStyle: { color: '#f59e0b' },
        areaStyle: { color: '#f59e0b', opacity: 0.1 }
      }
    ]
  };

  myChart.setOption(option);
  

// 监听窗口大小变化，自动调整图表大小
  window.addEventListener("resize", () => {
    if (myChart.value) {
      myChart.value.resize();
    }
  });
}

// 附近城市的location ID
const cityIds = [
  "101200501", // 黄冈市
  "101200301", // 鄂州市
  "101200401", // 孝感市
  "101200601", // 黄石市
  "101200701", // 咸宁市
  "101201301", // 随州市
  "101251001", // 岳阳市
  "101240201", // 九江市
  "101180601", // 信阳市
];

// 城市ID与名称的映射
const cityNames = {
  101200501: "黄冈市",
  101200301: "鄂州市",
  101200401: "孝感市",
  101200601: "黄石市",
  101200701: "咸宁市",
  101201301: "随州市",
  101251001: "岳阳市",
  101240201: "九江市",
  101180601: "信阳市",
};
// 存储所有城市天气数据的对象
const storedWeatherData = {};
// 遍历所有城市并获取天气数据
cityIds.forEach((cityId) => {
  axios
    .get(
      `https://p76yvxv44n.re.qweatherapi.com/v7/weather/30d?location=${cityId}`,
      {
        headers: {
          Authorization:
            "Bearer eyJhbGciOiJFZERTQSIsImtpZCI6Iks0NUY1R0pRTVAifQ.eyJzdWIiOiI0OVRORjZRRUpWIiwiaWF0IjoxNzU3NTcwODgyLCJleHAiOjE3NTc2NTcyODJ9.tgyV0Ric5fuBRXxJjsF-p9k9qafhmprj7L-49FibuLDxj6iWMUh4VAjYrC7UJ-kFpo8kawH-2OLa20SI1h-ICQ",
        },
      }
    )
    .then(function (response) {
      // 获取当天天气数据
      const todayWeather = response.data.daily[0];

      // 存储数据
      storedWeatherData[cityId] = {
        name: cityNames[cityId],
        date: todayWeather.fxDate,
        dayWeather: todayWeather.textDay,
        nightWeather: todayWeather.textNight,
        maxTemp: todayWeather.tempMax,
        minTemp: todayWeather.tempMin,
        iconDay: todayWeather.iconDay,
      };

      // 检查是否所有城市数据都已获取
      if (Object.keys(storedWeatherData).length === cityIds.length) {
        console.log("所有城市数据已获取并存储完成!");
        console.log("存储的数据对象:", storedWeatherData);
      }
    })
    .catch(function (error) {
      console.error(`获取${cityNames[cityId]}天气数据失败:`, error.message);
    });
});
</script>
